<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="600px"
    :before-close="handleClose"
  >
    <div class="add-relation-content">
      <!-- 搜索用户 -->
      <el-form :model="searchForm" label-width="80px">
        <el-form-item label="搜索用户">
          <el-input
            v-model="searchForm.keyword"
            placeholder="输入用户ID、昵称或手机号搜索"
            clearable
            @input="handleSearch"
          >
            <template #append>
              <el-button icon="el-icon-search" @click="handleSearch" />
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <!-- 搜索结果 -->
      <div v-loading="searchLoading" class="search-results">
        <div v-if="searchResults.length > 0" class="results-list">
          <div class="results-header">
            <h4>搜索结果 ({{ searchResults.length }} 个)</h4>
          </div>
          
          <div class="user-list">
            <div
              v-for="user in searchResults"
              :key="user.id"
              class="user-item"
              :class="{ selected: selectedUser?.id === user.id }"
              @click="handleSelectUser(user)"
            >
              <el-avatar :src="getFullImageUrl(user.avatar_url)" :size="40">
                <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
              </el-avatar>
              
              <div class="user-info">
                <div class="user-name">{{ user.nickname || '未设置昵称' }}</div>
                <div class="user-details">
                  <span class="user-id">ID: {{ user.id }}</span>
                  <span class="user-phone">{{ user.phone || '未绑定手机' }}</span>
                </div>
              </div>
              
              <div class="user-status">
                <el-tag :type="user.is_active ? 'success' : 'danger'" size="small">
                  {{ user.is_active ? '活跃' : '禁用' }}
                </el-tag>
              </div>
              
              <div v-if="selectedUser?.id === user.id" class="selected-indicator">
                <el-icon class="check-icon"><check /></el-icon>
              </div>
            </div>
          </div>
        </div>
        
        <el-empty 
          v-else-if="hasSearched" 
          description="未找到匹配的用户" 
          :image-size="80" 
        />
        
        <div v-else class="search-tip">
          <el-icon class="tip-icon"><search /></el-icon>
          <p>请输入关键词搜索用户</p>
        </div>
      </div>

      <!-- 选中的用户信息 -->
      <div v-if="selectedUser" class="selected-user">
        <h4>选中的用户</h4>
        <div class="selected-user-card">
          <el-avatar :src="getFullImageUrl(selectedUser.avatar_url)" :size="50">
            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
          </el-avatar>
          
          <div class="selected-user-info">
            <div class="selected-user-name">{{ selectedUser.nickname || '未设置昵称' }}</div>
            <div class="selected-user-details">
              <span>ID: {{ selectedUser.id }}</span>
              <span>{{ selectedUser.phone || '未绑定手机' }}</span>
            </div>
          </div>
          
          <div class="relation-type-selector">
            <el-radio-group v-model="currentRelationType">
              <el-radio label="friend">好友</el-radio>
              <el-radio label="blacklist">黑名单</el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirm" 
          :disabled="!selectedUser"
          :loading="adding"
        >
          添加{{ currentRelationType === 'friend' ? '好友' : '黑名单' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { searchUsers, createUserRelation } from '@/api/user'

export default {
  name: 'AddRelationDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    userId: {
      type: [Number, String],
      required: true
    },
    relationType: {
      type: String,
      default: 'friend'
    }
  },
  emits: ['update:modelValue', 'added'],
  setup(props, { emit }) {
    const visible = ref(props.modelValue)
    const searchLoading = ref(false)
    const adding = ref(false)
    const hasSearched = ref(false)
    
    const searchResults = ref([])
    const selectedUser = ref(null)
    const currentRelationType = ref(props.relationType)

    // 搜索表单
    const searchForm = reactive({
      keyword: ''
    })

    // 对话框标题
    const dialogTitle = computed(() => {
      return currentRelationType.value === 'friend' ? '添加好友' : '添加黑名单'
    })

    // 监听对话框显示状态
    watch(() => props.modelValue, (val) => {
      visible.value = val
      if (val) {
        currentRelationType.value = props.relationType
        resetDialog()
      }
    })

    watch(visible, (val) => {
      emit('update:modelValue', val)
    })

    watch(() => props.relationType, (val) => {
      currentRelationType.value = val
    })

    // 重置对话框
    const resetDialog = () => {
      searchForm.keyword = ''
      searchResults.value = []
      selectedUser.value = null
      hasSearched.value = false
    }

    // 搜索用户
    const handleSearch = async () => {
      if (!searchForm.keyword.trim()) {
        searchResults.value = []
        hasSearched.value = false
        return
      }

      searchLoading.value = true
      hasSearched.value = true
      
      try {
        const response = await searchUsers({
          keyword: searchForm.keyword.trim(),
          exclude_user_id: props.userId // 排除当前用户
        })
        
        searchResults.value = response.data.users || []
      } catch (error) {
        ElMessage.error('搜索用户失败：' + error.message)
        searchResults.value = []
      } finally {
        searchLoading.value = false
      }
    }

    // 选择用户
    const handleSelectUser = (user) => {
      selectedUser.value = user
    }

    // 确认添加
    const handleConfirm = async () => {
      if (!selectedUser.value) {
        ElMessage.warning('请先选择一个用户')
        return
      }

      adding.value = true
      
      try {
        await createUserRelation({
          user_id: props.userId,
          target_user_id: selectedUser.value.id,
          relation_type: currentRelationType.value
        })

        const relationTypeText = currentRelationType.value === 'friend' ? '好友' : '黑名单'
        ElMessage.success(`${relationTypeText}添加成功`)
        
        emit('added')
        handleClose()
      } catch (error) {
        ElMessage.error('添加失败：' + error.message)
      } finally {
        adding.value = false
      }
    }

    // 关闭对话框
    const handleClose = () => {
      visible.value = false
      resetDialog()
    }

    function getFullImageUrl(url) {
      if (!url) return '';
      if (/^https?:\/\//.test(url)) return url;
      if (url.startsWith('/uploads/avatar/')) return imageBaseUrl.value + url;
      return `${imageBaseUrl.value}/uploads/avatar/${url.replace(/^uploads[\/\\]avatar[\/\\]/, '')}`;
    }
    const imageBaseUrl = ref(process.env.VUE_APP_IMAGE_BASE_URL || 'https://hm.yunxitech.cn');

    return {
      visible,
      searchLoading,
      adding,
      hasSearched,
      searchResults,
      selectedUser,
      currentRelationType,
      searchForm,
      dialogTitle,
      handleSearch,
      handleSelectUser,
      handleConfirm,
      handleClose,
      getFullImageUrl
    }
  }
}
</script>

<style scoped>
.add-relation-content {
  max-height: 500px;
  overflow-y: auto;
}

.search-results {
  margin: 20px 0;
  min-height: 200px;
}

.results-header {
  margin-bottom: 15px;
}

.results-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.user-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #fafafa;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.user-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.user-item.selected {
  border-color: #409eff;
  background-color: #e1f3d8;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.user-details {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #909399;
}

.user-status {
  flex-shrink: 0;
}

.selected-indicator {
  position: absolute;
  top: 5px;
  right: 5px;
  color: #67c23a;
}

.check-icon {
  font-size: 18px;
}

.search-tip {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.tip-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.search-tip p {
  margin: 0;
  font-size: 14px;
}

.selected-user {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.selected-user h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.selected-user-card {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  border: 1px solid #67c23a;
  border-radius: 8px;
  background-color: #f0f9ff;
}

.selected-user-info {
  flex: 1;
}

.selected-user-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.selected-user-details {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #606266;
}

.relation-type-selector {
  flex-shrink: 0;
}

:deep(.el-radio-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-radio) {
  margin-right: 0;
}
</style> 